<script setup>
import { Upload } from '@element-plus/icons-vue'

const props = defineProps({
    dialog: { type: Boolean, default: false },//是否是在dialog中显示
})
const emits = defineEmits(['status'])
const route = useRoute()
const router = useRouter()

const status = reactive({
    editData: !props.dialog && route.query.id,//是否编辑数据
    submitLoading: false,//提交按钮点击时的等待效果
})
const data = reactive({
    data: {},//数据
    power: {},//权限显示
})
const rules = reactive({
    name: [{ required: true, min: 2, max: 10, message: '管理组名称必须在2~10个字符之间', trigger: 'blur' }],
})
const formRef = ref()

onMounted(() => {
    getData()
})

const keyToChinese = (key) => {
    switch (key) {
        //功能
        case 'uploads': return '上传'; break;
        case 'admin': return '管理员'; break;
        case 'adminGroup': return '管理组'; break;
        case 'article': return '文章'; break;
        case 'articleType': return '文章类型'; break;
        //自定义方法
        case 'image': return '图片'; break;
        case 'video': return '视频'; break;
        //通用方法
        case 'info': return '查看详情'; break;
        case 'list': return '列表'; break;
        case 'listExport': return '导出'; break;
        case 'edit': return '新增/修改'; break;
        case 'delete': return '删除'; break;
        default: return key; break;
    }
}
//获取信息
const getData = async () => {
    await axios.get('/adminGroup/info', {
        params: { id: !props.dialog ? route.query.id : 0 }
    }).then(response => {
        data.data = response.data
        powerDisplay()
    })
}
//提交信息
const submit = (form) => {
    //赋值权限
    const power = []
    for (const i in data.power) {
        power.push(...data.power[i].checked)
    }
    data.data.power = power
    //提交信息
    form.validate((valid, fields) => {
        if (!valid) return false
        status.submitLoading = true
        axios.post('/adminGroup/edit', {
            ...data.data
        }).then(async response => {
            sys.tip(response)
            if (response.status == 1) {
                getData()
                emits('status', { update: true })
            }
            setTimeout(() => { status.submitLoading = false }, 500)
        }).catch(error => {
            setTimeout(() => { status.submitLoading = false }, 500)
        })
    })
}
//权限整理
const powerDisplay = () => {
    const allPower = {}
    for (const i in data.data.allPower) {
        const item = data.data.allPower[i]
        const ca = item.split('/')
        //定义权限字段
        if (!allPower[ca[0]]) {
            allPower[ca[0]] = {
                title: keyToChinese(ca[0]),
                key: ca[0],
                children: [],
                checked: [],
                indeterminate: false,
                checkedAll: false
            }
        }
        allPower[ca[0]].children.push({ title: keyToChinese(ca[1]), key: item })
        //如果data中有权限则加入选择
        if (data.data.power && data.data.power.includes(item)) allPower[ca[0]].checked.push(item)
    }
    //checkedAll选中状态
    for (const i in allPower) {
        const item = allPower[i]
        const allCount = Object.keys(item.children).length
        const checkedCount = Object.keys(item.checked).length
        if (checkedCount == 0) {
            item.checkedAll = false
            item.indeterminate = false
        } else if (checkedCount > 0 && checkedCount < allCount) {
            item.checkedAll = false
            item.indeterminate = true
        } else if (checkedCount == checkedCount) {
            item.checkedAll = true
            item.indeterminate = false
        }
    }
    data.power = allPower
}
//全选
const changeAll = (item) => {
    item.indeterminate = false
    if (item.checkedAll) {
        item.checked = item.children.map((item) => item.key)
    } else {
        item.checked = []
    }
}
//单选

const changeOne = (item) => {
    const allCount = Object.keys(item.children).length
    const checkedCount = Object.keys(item.checked).length
    if (checkedCount == 0) {
        item.checkedAll = false
        item.indeterminate = false
    } else if (checkedCount > 0 && checkedCount < allCount) {
        item.checkedAll = false
        item.indeterminate = true
    } else if (checkedCount == checkedCount) {
        item.checkedAll = true
        item.indeterminate = false
    }
}
</script>

<template>
    <div>
        <Breadcrumb :title="['管理员', '管理组', status.editData ? '编辑' : '新增']" :path="['/admin/list', '/adminGroup/list']"
            :back="route.query.back" v-if="!props.dialog" />
        <el-card :class="{ 'el-card-dialog': props.dialog }">
            <template #header v-if="!props.dialog">
                <span>基本信息</span>
            </template>
            <el-form class="edit" ref="formRef" :model="data.data" :rules="rules">
                <el-form-item label="管理组名称" prop="name">
                    <el-input v-model="data.data.name" clearable />
                </el-form-item>
                <el-form-item label="可用权限" prop="power">
                    <div v-for="item in data.power" :key="item.key" class="power-checked flex">
                        <el-checkbox v-model="item.checkedAll" :indeterminate="item.indeterminate"
                            @change="changeAll(item)">
                            <el-text tag="b">{{ item.title }}</el-text>
                        </el-checkbox>
                        <el-text class="mr20 ml20" style="color: var(--el-border-color);">|</el-text>
                        <el-checkbox-group v-model="item.checked" @change="changeOne(item)">
                            <el-checkbox v-for="item2 in item.children" :key="item.key + '/' + item2.key"
                                :value="item2.key">
                                {{ item2.title }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-affix position="bottom" z-index="9">
                    <el-form-item label="&nbsp;" class="button-affix">
                        <el-button type="primary" :icon="Upload" v-if="$power('/adminGroup/edit')"
                            :loading="status.submitLoading" @click="submit(formRef)">提交</el-button>
                        <el-button v-if="status.editData" @click="getData()"
                            :disabled="status.submitLoading">刷新&重置</el-button>
                        <el-button :disabled="status.submitLoading" v-if="props.dialog" type="warning" plain
                            @click="emits('status', { close: true })">关闭</el-button>
                        <el-button :disabled="status.submitLoading" v-else type="warning" plain
                            @click="() => { router.push(route.query.back) }">返回</el-button>
                    </el-form-item>
                </el-affix>
            </el-form>
        </el-card>
    </div>
</template>

<style scoped lang="scss">
.power-checked {
    width: 100%;
    border-bottom: 1px dashed var(--el-border-color);
    padding-bottom: 5px;
    margin-bottom: 5px;
}
</style>
